package cn.wolfcode.wms.web.introceptor;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.utils.PermissionUtil;
import cn.wolfcode.wms.utils.RequirePermission;
import cn.wolfcode.wms.utils.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class SecurityInterceptor extends HandlerInterceptorAdapter{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        Employee employee = UserContext.getEmployee();
        //若该用户是超级管理员则放行
        if(employee.isAdmin()){

            return true;
        }
        //判断请求的方法是否含有@RequiredPermission标签
        HandlerMethod hmethod = (HandlerMethod) (handler);
        Method method = hmethod.getMethod();

        if(!method.isAnnotationPresent(RequirePermission.class)){
                return true;
        }
        //判断该请求的方法的权限表达式
        String expression = PermissionUtil.getExpression(method);
        List<String> expressions = UserContext.getExpression();
        if (expressions.contains(expression)){
            return true;
        }
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp")
                .forward(request,response);
        return  false;
    }
}
